package com.ruoyi.proposal.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.proposal.dto.ProposalDTO;
import com.ruoyi.proposal.dto.ProposalQueryDTO;
import com.ruoyi.proposal.service.ProposalService;
import com.ruoyi.proposal.vo.ProposalVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 提案控制器
 * d对应前端submit.vue页面
 */
@RestController
@RequestMapping("/proposal/submit")
public class ProposalSubmitController extends BaseController {

    @Autowired
    private ProposalService proposalService;

    /**
     * 提交提案
     * @param proposalDTO 提案数据传输对象
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermi('proposal:submit:add')")
    @Log(title = "提案提交", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submitProposal(@RequestBody ProposalDTO proposalDTO) {
        try {
            // 设置默认状态
            if (proposalDTO.getStatus() == null || proposalDTO.getStatus().isEmpty()) {
                proposalDTO.setStatus("待审核");
            }

            // 提交提案
            proposalService.submitProposal(proposalDTO);
            return AjaxResult.success("提案提交成功");
        } catch (Exception e) {
            return AjaxResult.error("提案提交失败: " + e.getMessage());
        }
    }

    /**
     * 查询所有提案
     * @param queryDTO 查询条件
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermi('proposal:list')")
    @GetMapping("/list")
    public TableDataInfo listProposals(ProposalQueryDTO queryDTO) {
        //com.github.pagehelper.PageHelper.startPage(queryDTO.getPageNum(), queryDTO.getPageSize());
        List<ProposalVO> proposals = proposalService.findAllProposals(queryDTO);
        return getDataTable(proposals);
    }

    /**
     * 更新提案
     * @param proposalDTO 提案数据传输对象
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermi('proposal:edit')")
    @Log(title = "提案管理", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult updateProposal(@RequestBody ProposalDTO proposalDTO) {
        try {
            // 更新提案
            proposalService.updateProposal(proposalDTO);
            return AjaxResult.success("更新成功");
        } catch (Exception e) {
            return AjaxResult.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 查询财务相关提案
     * @param queryDTO 查询条件
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermi('proposal:finance:list')")
    @GetMapping("/finance/list")
    public TableDataInfo listFinanceProposals(ProposalQueryDTO queryDTO) {
        startPage();
        List<ProposalVO> proposals = proposalService.findFinanceProposals(queryDTO);
        return getDataTable(proposals);
    }

    /**
     * 更新节省金额
     * @param proposalDTO 提案数据传输对象
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermi('proposal:finance:edit')")
    @Log(title = "财务审核", businessType = BusinessType.UPDATE)
    @PutMapping("/finance/savings")
    public AjaxResult updateSavings(@RequestBody ProposalDTO proposalDTO) {
        try {
            // 更新节省金额
            proposalService.updateSavings(proposalDTO);
            return AjaxResult.success("节省金额更新成功");
        } catch (Exception e) {
            return AjaxResult.error("节省金额更新失败: " + e.getMessage());
        }
    }

    /**
     * 查询待打分提案
     * @param queryDTO 查询条件
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermi('proposal:score:list')")
    @GetMapping("/score/list")
    public TableDataInfo listScoreProposals(ProposalQueryDTO queryDTO) {
        startPage();
        List<ProposalVO> proposals = proposalService.findScoreProposals(queryDTO);
        return getDataTable(proposals);
    }

    /**
     * 提交评分
     * @param proposalDTO 提案数据传输对象
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermi('proposal:score:edit')")
    @Log(title = "评分管理", businessType = BusinessType.UPDATE)
    @PostMapping("/score")
    public AjaxResult submitScore(@RequestBody ProposalDTO proposalDTO) {
        try {
            // 计算奖金（与前端逻辑保持一致）
            if (proposalDTO.getCommitteeTotalScore() != null) {
                double avgScore = ((proposalDTO.getSupervisorTotalScore() != null ? proposalDTO.getSupervisorTotalScore() : 0) +
                        (proposalDTO.getManagerTotalScore() != null ? proposalDTO.getManagerTotalScore() : 0) +
                        proposalDTO.getCommitteeTotalScore()) / 3.0;
                proposalDTO.setBonus(java.math.BigDecimal.valueOf(avgScore * 10));
            }

            // 提交评分
            proposalService.submitScore(proposalDTO);
            return AjaxResult.success("评分提交成功");
        } catch (Exception e) {
            return AjaxResult.error("评分提交失败: " + e.getMessage());
        }
    }
}